package cre.tool.core;

import cre.tool.util.AES;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author penglai
 * @Date 2017/2/24.
 */
public class Configuration {

    public static final String TOOL_HOME = System.getProperty("user.dir");
    public static final String FILE_DIR = "/file";
    public static final String CONF_DIR = "/conf";

    public static final String DEFAULT_CONFIG = "tool.properties";
    public static final String SUBS_CONFIG = "sub-category.properties";
    public static final String EXCEL_SUFFIX = ".xlsx";

    public static final String SUB_FILE = "sub.xlsx";
    public static final String EXPORT_FILE = "export.xlsx";
    public static final String IMPORT_FILE = "import.xlsx";
    public static final String ALBUM_INFO_FILE = "album-info.xlsx";
    public static final String ALBUM_INFO_EXPORT_FILE = "album-info-export.xlsx";

    private static org.apache.commons.configuration.Configuration configuration;
    private static Map<String, Integer> categoryMap = null;

    static {
        try {
            configuration = new PropertiesConfiguration(TOOL_HOME + CONF_DIR + "/" + DEFAULT_CONFIG);
//            test();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static void test(){
        Iterator<String> iterator = configuration.getKeys();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(key + ": " + configuration.getString(key));
        }
    }

    private static String categoryId;

    private static void initCategoryMap() {
        try {
            categoryMap = new HashMap<>();
            configuration = new PropertiesConfiguration(TOOL_HOME + CONF_DIR + "/" + SUBS_CONFIG);

            Iterator<String> keys = configuration.getKeys();
            while (keys.hasNext()) {
                String key = keys.next();
                categoryMap.put(configuration.getString(key), Integer.valueOf(key));
            }
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static String getString(String s) {
        return configuration.getString(s);
    }

    public static String getString(String s, String s1) {
        return configuration.getString(s, s1);
    }

    public static Map<String, Integer> getCategoryMap() {
        if (categoryMap == null) {
            initCategoryMap();
        }
        return categoryMap;
    }

    private static String decode(String password){
        return AES.decrypt(password);
    }

    public static String getUrl() {
        return decode(getString("db_url"));
    }

    public static String getUser() {
        return decode(getString("db_user"));
    }

    public static String getPassword() {
        return decode(getString("db_pwd"));
    }
}
